// JavaScript Document
//请款单
$(document).ready(load_init);
$(window).resize(load_init);

using('messager', function () {
    $.messager.progress({
        title: '提示',
        text: '系统加载中，请稍后....'
    });
    page_init();
});

var InvoiceTable;
var NewInvoiceBox;
var ProjectBox;
var projectfilestable;
var rowindex=-1;

var textsetting={
   	buttonText:'选择',
    buttonIcon:'icon-more',
	editable:false,
	required:true,
	onClickButton:function(){
		ProjectBox.dialog("open");
	}
	};



function load_init()
{
	var height=$(window).height();
	$("#InvoiceTableBox").height(height-150);
}

function page_init()
{
	using(["layout","validatebox",'panel', 'dialog','datagrid','accordion','linkbutton','textbox','combobox',"datebox","form"], function () {
		using("plugins/jquery.edatagrid.js", function(){window.setTimeout(edatagrid_init,0);});
		input_init();
		layout_init();
		queryinput_init();
		table_init();
		InvoiceBox_init();
		ProjectBox_init();
		$.messager.progress('close');
	});
}


function dateChange(newValue,oldValue){
					var lease_begindate=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"lease_begindate"});
					var lease_enddate=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"lease_enddate"});
					var lease_days=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"lease_days"});
					var reg=/^[1|2]\d{3}-\d{1,2}-\d{1,2}$/;
					if(lease_begindate!=null&&lease_enddate!=null)
					{
					var begindate=$(lease_begindate.target).datebox("getValue");
					var enddate=$(lease_enddate.target).datebox("getValue");
					if(reg.test(enddate)&&reg.test(begindate))
					{
						
						if(reg.test(begindate))
						{
							var dat1 = new Date(begindate).getTime();
							var dat2 = new Date(enddate).getTime();
							var str = Math.floor((dat2 - dat1)/1000/60/60/24);
							if(str<0)
							{
								$.messager.alert('提示','截止日不能小于起租日！','info');
								$(lease_enddate.target).datebox("setValue","");
								return;
							}
							$(lease_days.target).textbox("setValue",str+1);
							calculate(newValue,oldValue);
						}
					}
					}
}

function edatagrid_init()
{
	InvoiceTable=$("#InvoiceTable").edatagrid({
			method:"post",
			//url:webpath+"DeviceManage/QueryDeviceMan",
			//saveUrl: webpath+"INVOICE/AddProjectFile",
            //updateUrl: webpath+'DeviceManage/EditClassify',
            //destroyUrl: webpath+'DeviceManage/DelClassify',
			idField:"probill_uuid",
			singleSelect:true,
			rownumbers:true,
			fit:true,
			fitColumns:true,
			nowrap : false,
			showFooter:true,
			columns:[[
				{field:'probill_uuid',hidden:true},
				{field:'proinfo_uuid',hidden:true},
				{field:'clientinfo_uuid',hidden:true},
				{field:'proarc_uuid',hidden:true},
				{field:'proarc_number',hidden:true},
				{field:'engineer_name',hidden:true},
				{field:'pro_address',hidden:true},
				{field:'pro_time',hidden:true},
				{field:'lease_begindate',title:'起租日',fixed:true,width:100,
				editor:{type:'datebox',options:{required:true,validType:"checkDate",
				onChange:dateChange
				}}},
				{field:'lease_enddate',title:'截止日',fixed:true,width:100,
				editor:{type:'datebox',options:{required:true,validType:"checkDate",
				onChange:dateChange
				}}},
				{field:'lease_days',title:'日数',fixed:true,width:100,
				editor:{type:'textbox',options:{editable:false}}},
				{field:'device_number',title:'台数',fixed:true,width:100,
				editor:{type:'textbox',options:{required:true,validType:"checkNum",
				onChange:calculate
				}}},
				{field:'device_price',title:'单价',fixed:true,width:100,
				editor:{type:'textbox',options:{required:true,validType:"checkFloat",
				onChange:calculate}}},
				{field:'lease_total',title:'小计',fixed:true,width:100,
				editor:{type:'textbox',options:{editable:false}}}
        	]],
			onBeforeEdit:function(index,row){
				rowindex=index;
			},
			onEndEdit:function(index,row,changes){
				rowindex=-1;
				calculatetotal();
			},
			onLoadSuccess:function(data){
				rowindex=-1;
				calculatetotal();
			},
			onSuccess:function(){
			 	$(InvoiceTable).edatagrid("reload");
			},
			toolbar: [
			{
			iconCls: 'icon-new',
			text:"新建请款单",
			handler: function(){
				$.messager.confirm('确认','确认新建请款单信息吗?<br />新建后将清空当前界面数据。',function(r){
						if(r){
								cleanInvoice();
							}
						});
				}
			},'-',
			{
			iconCls: 'icon-add',
			text:"添加",
			handler: function(){
				var proinfo_uuid=$("#proinfo_uuid").val();
				var probill_number=$("#probill_number").val();
				if(probill_number=="-1"||probill_number=="")
				{
				if(proinfo_uuid=="")
				{
					$.messager.alert('提示','请先选择项目信息','info');
					return;
				}
				
				var date=$("#date").datebox("getValue");
				if(date=="")
				{
					$.messager.alert('提示','请选择请款日期','info');
					return;
				}
				
				var engineer_name=$("#engineer_name").textbox("getValue");
				if(date=="")
				{
					$.messager.alert('提示','请输入工程名称!','info');
					return;
				}
				
				var pro_address=$("#pro_address").textbox("getValue");
				if(pro_address=="")
				{
					$.messager.alert('提示','请输入工程地址!','info');
					return;
				}
				
				$(InvoiceTable).edatagrid('addRow');
				}else
				{
					$.messager.alert('提示','当前信息已保存，请新建请款单!','info');
				}
				}
			},{
			iconCls: 'icon-remove',
			text:"删除",
			handler: function(){
				var probill_number=$("#probill_number").val();
				if(probill_number=="-1"||probill_number=="")
				{
					$(InvoiceTable).edatagrid('destroyRow');
				}else
				{
					$.messager.alert('提示','当前信息已保存，请新建请款单!','info');
				}
				}
			},
			{
			iconCls: 'icon-save',
			text:"保存",
			handler: function(){
				var probill_number=$("#probill_number").val();
				if(probill_number=="-1"||probill_number=="")
				{
				$(InvoiceTable).edatagrid('saveRow');
				$.messager.confirm('确认','确认保存请款单吗?<br />保存成功后界面数据将不可修改！',function(r){
						if(r){
								SaveInvoice();
							}
						});
				}else
				{
					$.messager.alert('提示','当前信息已保存，请新建请款单!','info');
				}		
				}
			},
			'-',
			{
			iconCls: 'icon-reload',
			text:"刷新",
			handler: function(){
				$(InvoiceTable).datagrid("reload");
				}
			}
			],
			onAdd:function(index, row){
				var proinfo_uuid=$("#proinfo_uuid").val();
				var clientinfo_uuid=$("#clientinfo_uuid").val();
				var proarc_uuid=$("#proarc_uuid").val();
				var date=$("#date").datebox("getValue");
				var engineer_name=$("#engineer_name").textbox("getValue");
				var pro_address=$("#pro_address").textbox("getValue");
				var proarc_number=$("#proarc_number").textbox("getValue");
				
				row.proinfo_uuid=proinfo_uuid;
				row.clientinfo_uuid=clientinfo_uuid;
				row.proarc_uuid=proarc_uuid;
				row.pro_time=date;
				row.engineer_name=engineer_name;
				row.pro_address=pro_address;
				row.proarc_number=proarc_number;
			},
			onSave:function(index,row){
				
			}
	});
	
	$(InvoiceTable).edatagrid('reloadFooter',[
	{device_price: '总计:', lease_total: 0}
	]);
}

function cleanInvoice()
{
	$("#client_name").textbox("setValue","");
	$("#proarc_number").textbox("setValue","");
	$("#pro_name").textbox("setValue","");
	$("#date").datebox("setValue","");
	$("#engineer_name").textbox("setValue","");
	$("#pro_address").textbox("setValue","");
	$("#proinfo_uuid").val("");
	$("#clientinfo_uuid").val("");
	$("#proarc_uuid").val("");
	$("#probill_number").val("-1");
	InvoiceTable.edatagrid("loadData",{rows:[],total:0});
}

function calculate(newValue,oldValue)
{
	if(rowindex!=-1){
	var device_number=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"device_number"});
	var device_price=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"device_price"});
	var lease_days=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"lease_days"});
	var lease=$(lease_days.target).textbox("getValue");
	var price=$(device_price.target).textbox("getValue");
	var number=$(device_number.target).textbox("getValue");
	var lease_total=$(InvoiceTable).edatagrid('getEditor', {index:rowindex,field:"lease_total"});
	var reg1=/^([0-9]+)$/;
	var reg2=/^[+|-]?([0-9]+\.[0-9]+)|[0-9]+$/;
	
	if(reg1.test(lease)&&reg1.test(number)&&reg2.test(price))
	{
		$(lease_total.target).textbox("setValue",mul(mul(lease,price),number));
	}
	}
}

function calculatetotal()
{
	var rows=$(InvoiceTable).edatagrid("getRows");
	var tmp=0.0;
	for(var i=0;i<rows.length;i++)
	{
		tmp=add(tmp,rows[i].lease_total);
	}
	
	$(InvoiceTable).edatagrid('reloadFooter',[
	{device_price: '总计:', lease_total: tmp}
	]);
	
}

function ProjectBox_init()
{
	ProjectBox=$("#ProjectBox").dialog(
	{
			title: '选择项目信息',
			width: 700,
			height: 450,
			closed: true,
			cache: false,
			modal: true,
			buttons:[
				{
				text:'选择',
				iconCls:'icon-ok',
				handler:function(){
					selectquery();
					}
			},{
				text:'关闭',
				iconCls:'icon-cancel',
				handler:function(){
					cleanquery();
					}
			}
			]
	}
	);
	$("#ProjectBox").css("visibility","visible");
}

function cleanquery()
{
	$("#QueryCustomerId").textbox("setValue","");
	$("#QueryProjectNameId").textbox("setValue","");
	$("#QueryProjectDateStart").datebox("setValue","");
	$("#QueryProjectDateEnd").datebox("setValue","");
	projectfilestable.datagrid("loadData",{rows:[],total:0});
	ProjectBox.dialog("close");
}

function selectquery()
{
	var node=projectfilestable.datagrid("getSelected");
	if(node==null)
	{
		$.messager.alert('提示','请先选择需要的项目','info');
		return;
	}
	$("#proinfo_uuid").val(node.proinfo_uuid);
	$("#clientinfo_uuid").val(node.clientinfo_uuid);
	$("#proarc_uuid").val(node.proarc_uuid);
	$("#client_name").textbox("setValue",node.client_name);
	$("#proarc_number").textbox("setValue",node.proarc_number);
	$("#pro_name").textbox("setValue",node.pro_name);
	/*$(InvoiceTable).edatagrid({
						url:webpath+"INVOICE/getInvoiceInfos",
						queryParams:{
							uuid: node.proarc_uuid
						}
						});*/
	
	/*$.post(webpath+"INVOICE/getInvoiceInfo",
		{uuid:node.proarc_uuid}
	,function(data){
		 if(data.code=="200")
		 {
			$("#date").datebox("setValue",data.data.pro_time);
			$("#engineer_name").textbox("setValue",data.data.pro_address);
			$("#pro_address").textbox("setValue",data.data.engineer_name);
		 }
		},"json");	*/			
	
	cleanquery();
}

function InvoiceBox_init()
{
	NewInvoiceBox=$("#NewInvoiceBox").dialog({
		    title: '新建请款单',
			width: 700,
			height: 450,
			closed: true,
			cache: false,
			modal: true,
			onClose:function(){
				//$("#NewProjectFiles").form("clear");
			},
			buttons:[{
				text:'保存',
				iconCls:'icon-save',
				handler:function(){
					
					}
			},{
				text:'关闭',
				iconCls:'icon-no',
				handler:function(){NewInvoiceBox.dialog("close");}
			}]
		});
		
	$("#NewInvoiceBox").css("visibility","visible");
}

function input_init()
{
	$("#proarc_number").textbox(textsetting);
	$("#client_name").textbox(textsetting);
	$("#pro_name").textbox(textsetting);
	$("#date").datebox({
			required:true,
			validType:"checkDate"
			});
	$("#engineer_name").textbox({required:true});
	$("#pro_address").textbox({required:true});
}

function queryinput_init()
{
	$("#QueryBtn").linkbutton({
			onClick:function(){
				projectfilestable.datagrid({
					url:webpath+"ProjectFiles/QueryProjectFiles",
					queryParams:{
						QueryCustomerId:$("#QueryCustomerId").textbox("getValue"),
						QueryProjectNameId:$("#QueryProjectNameId").textbox("getValue"),
						QueryProjectDateStart:$("#QueryProjectDateStart").datebox("getValue"),
						QueryProjectDateEnd:$("#QueryProjectDateEnd").datebox("getValue")
						}
					});
			}
		});
}


function layout_init()
{
	$("#INVOICElayout").layout({fit:true});
	$("#projectfileslayout").layout({fit:true});
}

function table_init()
{

	projectfilestable=$("#projectfilestable").datagrid(
		{
			method:"post",
			//url:webpath+"ProjectFiles/QueryProjectFiles",
			singleSelect:true,
			rownumbers:true,
			fit:true,
			fitColumns:true,
			pageSize : 10,
			pageList : [ 10,15, 25, 35, 45, 55,65,100],
			nowrap : false,
			pagination:true,
			showFooter:true,
			columns:[[
				{field:'proarc_uuid',hidden:true},
				{field:'proinfo_uuid',hidden:true},
				{field:'clientinfo_uuid',hidden:true},
				{field:'proarc_number',title:'项目档案编号',fixed:true},
				{field:'client_name',title:'客户名称',fixed:true,width:100},
				{field:'pro_name',title:'项目名称',fixed:true,width:100},
				{field:'procha_name',title:'项目负责人',fixed:true},
				//{field:'engineer_name',title:'工程名称',fixed:true,width:100},
				//{field:'pro_address',title:'工程地址',fixed:true},
				{field:'inv_category',title:'发票类别',fixed:true},
				{field:'probegin_date',title:'项目起时间',fixed:true},
				{field:'proend_date',title:'项目止时间',fixed:true},
				{field:'procheck_date',title:'检测时间',fixed:true},
				{field:'proreport_date',title:'报告时间',fixed:true}
        	]],
			onDblClickCell:selectquery
		}
	);
}

function SaveInvoice()
{
	if(rowindex==-1)
	{
					var rows=$(InvoiceTable).edatagrid("getRows");
					
					if(rows.length<1)
					{
						$.messager.alert("提示","请先录入请款单再提交!","info");
						return;
					}
					
					$.messager.progress({title: '提示',text:"数据提交中....."});
					
					$.post(webpath+"INVOICE/AddInvoice",{
						"pro_time":$("#date").datebox("getValue"),
						"proarc_number":$("#proarc_number").textbox("getValue"),
						"proarc_uuid":$("#proarc_uuid").val(),
						"engineer_name":$("#engineer_name").textbox("getValue"),
						"pro_address":$("#pro_address").textbox("getValue"),
						"rows":rows},function(data){
							if(data.code==200)
							{
								$("#probill_number").val(data.message);
								$.messager.alert('提示',data.msg,'info');
							}
							else
							{
								$("#probill_number").val("-1");
								$.messager.alert('提示',data.msg,'info');
							}
						$.messager.progress("close");
					},"json");

	}
}